package com.ybxx.base.action;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import antlr.StringUtils;

import com.ybxx.base.model.Ban;
import com.ybxx.base.model.ChargeRule;
import com.ybxx.base.model.Community;
import com.ybxx.base.model.Room;
import com.ybxx.base.model.Rule;
import com.ybxx.base.model.RuleValue;
import com.ybxx.base.model.Unit;
import com.ybxx.base.service.ChargeRuleService;
import com.ybxx.base.service.CommunityService;
import com.ybxx.base.service.RuleService;
import com.ybxx.base.service.RuleValueService;
import com.ybxx.core.command.QueryFilter;
import com.ybxx.core.util.StringUtil;
import com.ybxx.core.util.UUIDGenerator;
import com.ybxx.core.web.action.BaseAction;
import com.ybxx.system.SystemConstants;
import com.ybxx.system.model.User;

public class CommunityAction extends BaseAction {
	@Resource
	private CommunityService communityService;
	@Resource
	private RuleService ruleService;
	@Resource
	private RuleValueService ruleValueService;
	@Resource
	private ChargeRuleService chargeRuleService;
	private List<Community> communitys;
	private List<Rule> rules;
	private List<Ban> bans;
	private List<ChargeRule> chargeRules;
	private Community community;
	private JSONObject resultObj;
	private String msg="succ";
	
	/*保存暖气费*/
	public String saveHealthFees(){
		try{
			communityService.saveHealthFees(community);
		}catch(Exception ex){
			msg="房费维护失败";
		}finally{
			return "succ";
		}
	}
	/*加载暖气费*/
	public String loadHealth(){
		communitys=communityService.queryDataRightsAll();
		return "loadHealth";
	}
	/*保存房费数据*/
	public String saveRoomFees(){
		try{
			communityService.saveRoomFees(community);
		}catch(Exception ex){
			msg="房费维护失败";
		}finally{
			return "succ";
		}
	}
	/*加载
	/*加载房费数据*/
	public String loadRoomFees(){
		chargeRules=chargeRuleService.getAll();
		communitys=communityService.queryDataRightsAll();
		return "loadRoomFees";
	}
	/*保存管理费数据*/
	public String saveGLF(){
		try{
			communityService.saveGLF(community);
		}catch(Exception ex){
			msg="管理费维护失败";
		}finally{
			return "succ";
		}
	}
	/*加载管理费数据*/
	public String loadGL(){
		chargeRules=chargeRuleService.getAll();
		communitys=communityService.queryDataRightsAll();
		return "loadGL";
	}
	/*保存护楼费数据*/
	public String saveBuildCharge(){
		try{
			communityService.saveBuildCharge(community);
		}catch(Exception ex){
			ex.printStackTrace();
			msg="护楼费维护失败.";
		}finally{
			return "succ";
		}
	}
	/**加载护楼费数据*/
	public String loadBuildCharge(){
		communitys=communityService.queryDataRightsAll();
		return "loadBuildCharge";
	}
	
	/*保存套户资料*/
	public String saveTH(){
		
		JSONArray root = JSONArray.fromObject(msg);
		List<Ban> bans=new ArrayList<Ban>();
		JSONObject obj=(JSONObject)root.get(0);		
		JSONArray banArray=obj.getJSONArray("children");
		for(int i=0;i<banArray.size();i++){
			JSONObject banJSON=banArray.getJSONObject(i);
			Ban ban=new Ban();
			String bid=banJSON.getString("id");
			if(banJSON.getString("id").startsWith("T")){
				bid=UUIDGenerator.getUUID();
			}
			ban.setBid(bid);
			ban.setBname(banJSON.getString("name"));
			ban.setState("0");
			JSONArray unitArray=banJSON.getJSONArray("children");
			for(int j=0;j<unitArray.size();j++){
				JSONObject unitJSON=unitArray.getJSONObject(j);
				Unit unit=new Unit();
				String uid=unitJSON.getString("id");
				if(unitJSON.getString("id").startsWith("T")){
					uid=UUIDGenerator.getUUID();
				}
				unit.setUid(uid);
				unit.setUname(unitJSON.getString("name"));
				unit.setBan(ban);
				unit.setState("0");
				ban.getUnits().add(unit);
				JSONArray roomArray=unitJSON.getJSONArray("children");
				for(int m=0;m<roomArray.size();m++){
					JSONObject roomJSON=roomArray.getJSONObject(m);
					Room room=new Room();
					String rid=roomJSON.getString("id");
					if(roomJSON.getString("id").startsWith("T")){
						rid=UUIDGenerator.getUUID();
					}
					room.setRid(rid);
					room.setRcode(roomJSON.getString("name"));
					room.setUnit(unit);
					room.setState("0");
					unit.getRooms().add(room);
				}
			}
			bans.add(ban);
		}
		try{
			communityService.saveTH(community,bans);
			msg="succ";
		}catch(Exception ex){
			ex.printStackTrace();
			msg="套户资料保存失败";
		}
		return "succ";
	}
	/**生成套户资料*/
	public String generator(){
		JSONArray arrayOne =new JSONArray();
		int cnum=Integer.parseInt(community.getCnum());
		int unum=Integer.parseInt(community.getUnum());
		int lnum=Integer.parseInt(community.getLnum());
		int rnum=Integer.parseInt(community.getRnum());
		/**检查套户资料开始*/
		Rule crule=(Rule)ruleService.get(community.getCrule().getRcode());
		if(crule.getIschar().equals("0")){
			if(cnum>Integer.parseInt(crule.getRcapity())){
				msg="你选择的楼栋数大于该规则（"+crule.getRcontent()+"）所支持的"+crule.getRcapity()+"的上限";
				return "succ";
			}
		}
		Rule urule=(Rule)ruleService.get(community.getUrule().getRcode());
		if(urule.getIschar().equals("0")){
			if(unum>Integer.parseInt(urule.getRcapity())){
				msg="你选择的楼栋数大于该规则（"+urule.getRcontent()+"）所支持的"+urule.getRcapity()+"的上限";
				return "succ";
			}
		}
		Rule lrule=(Rule)ruleService.get(community.getLrule().getRcode());
		if(lrule.getIschar().equals("0")){
			if(lnum>Integer.parseInt(lrule.getRcapity())){
				msg="你选择的楼栋数大于该规则（"+lrule.getRcontent()+"）所支持的"+lrule.getRcapity()+"的上限";
				return "succ";
			}
		}
		Rule rrule=(Rule)ruleService.get(community.getRrule().getRcode());
		if(rrule.getIschar().equals("0")){
			if(rnum>Integer.parseInt(rrule.getRcapity())){
				msg="你选择的楼栋数大于该规则（"+rrule.getRcontent()+"）所支持的"+rrule.getRcapity()+"的上限";
				return "succ";
			}
		}
		/*检查套户资料结束*/
		int llen=community.getLnum().length();
		List<Ban> bans=generatorBan(cnum);
		List<Unit> units=generatorUnit(unum);
		List<Room> rooms=generatorRoom(lnum,rnum,llen);
		JSONObject rootJSON=new JSONObject();
		rootJSON.put("id", community.getCid());
		rootJSON.put("name",community.getCname());
		rootJSON.put("pId","0");
		arrayOne.add(rootJSON);
		for(Iterator<Ban> iter=bans.iterator();iter.hasNext();){
			Ban ban=iter.next();
			String bid=UUIDGenerator.getUUID();
			JSONObject banJSON=new JSONObject();
			banJSON.put("id", bid);
			banJSON.put("name",ban.getBname());
			banJSON.put("pId",community.getCid());
			arrayOne.add(banJSON);
			for(Iterator<Unit> unit_Iter=units.iterator();unit_Iter.hasNext();){
				Unit unit=unit_Iter.next();
				String uid=UUIDGenerator.getUUID();
				JSONObject unitJSON=new JSONObject();
				unitJSON.put("id", uid);
				unitJSON.put("name",unit.getUname());
				unitJSON.put("pId",bid);
				arrayOne.add(unitJSON);
				for(Iterator<Room> room_Iter=rooms.iterator();room_Iter.hasNext();){
					Room room=room_Iter.next();
					String rid=UUIDGenerator.getUUID();
					JSONObject roomJSON=new JSONObject();
					roomJSON.put("id", rid);
					roomJSON.put("name",room.getRcode());
					roomJSON.put("pId",uid);
					arrayOne.add(roomJSON);
				}
			}
		}
		resultObj=new JSONObject();
		resultObj.put("community", arrayOne);
		
		return "generator";
	}
	private List<Room> generatorRoom(int lnum,int rnum,int llen){
		List<Room> rooms=new ArrayList<Room>();
		/*生成房号*/
		Rule lrule=(Rule)ruleService.get(community.getLrule().getRcode());
		List<RuleValue> lrvs=ruleValueService.queryRuleValues(community.getLrule().getRcode());
		Rule rrule=(Rule)ruleService.get(community.getRrule().getRcode());
		List<RuleValue> rrvs=ruleValueService.queryRuleValues(community.getRrule().getRcode());
		for(int i=1;i<=lnum;i++){
			for(int j=1;j<=rnum;j++){
				Room room=new Room();
				//楼层
				if(lrule.getIschar().equals("1")){//非字符
					room.setRcode(lpad(llen,i));
				}else{
					room.setRcode(lrvs.get(i-1).getRvalue());
				}
				//房间
				if(rrule.getIschar().equals("1")){//非字符
					room.setRcode(room.getRcode()+lpad(2,j));
				}else{
					room.setRcode(room.getRcode()+rrvs.get(j-1).getRvalue());
				}
				rooms.add(room);
			}
		}
		return rooms;
	}
	/**
     * 补齐不足长度
     * @param length 长度
     * @param number 数字
     * @return
     */
    private String lpad(int length, int number) {
        String f = "%0" + length + "d";
        return String.format(f, number);
    }

	private List<Unit> generatorUnit(int unum){
		List<Unit> units=new ArrayList<Unit>();
		/*生成单元数*/
		Rule rule=(Rule)ruleService.get(community.getUrule().getRcode());
		if(rule.getIschar().equals("1")){//非字符
			for(int i=Integer.parseInt(rule.getStart());i<=unum;i=i+Integer.parseInt(rule.getIncre())){
				Unit unit=new Unit();
				unit.setUname(i+"单元");
				units.add(unit);
			}
		}else{
			List<RuleValue> rvs=ruleValueService.queryRuleValues(community.getUrule().getRcode());
			for(int i=0;i<unum;i++){
				Unit unit=new Unit();
				unit.setUname(rvs.get(i).getRvalue()+"单元");
				units.add(unit);
			}
		}
		return units;
	}
	private List<Ban> generatorBan(int cnum){
		List<Ban> bans=new ArrayList<Ban>();
		/*生成楼栋数*/
		Rule rule=(Rule)ruleService.get(community.getCrule().getRcode());
		if(rule.getIschar().equals("1")){//非字符
			for(int i=Integer.parseInt(rule.getStart());i<=cnum;i=i+Integer.parseInt(rule.getIncre())){
				Ban ban=new Ban();
				ban.setBname(i+"栋");
				bans.add(ban);
			}
		}else{
			List<RuleValue> rvs=ruleValueService.queryRuleValues(community.getCrule().getRcode());
			for(int i=0;i<cnum;i++){
				Ban ban=new Ban();
				ban.setBname(rvs.get(i).getRvalue()+"栋");
				bans.add(ban);
			}
		}
		return bans;
	}
	/**用于套户资料修改查看*/
	public String loadHouse(){
		community=communityService.get(community.getCid());
		rules=ruleService.getAll();
		return "loadHouse";
	}
	/*删除小区*/
	public String remove(){
		try{
			communityService.remove(community.getCid());
		}catch(Exception ex){
			ex.printStackTrace();
			msg="该小区删除失败,只能禁用，不能删除";
		}finally{
			return "succ";
		}
	}
	/*用于为修改查询数据*/
	public String load(){
		community=communityService.get(community.getCid());
		return "load";
	}
	/*用于修改，新增小区保存*/
	public String save(){
		try{
			if(community!=null && "".equals(community.getCid())){
				community.setCid(UUIDGenerator.getUUID());
				communityService.save(community);
			}else{
				Community tmp=communityService.get(community.getCid());
				tmp.setCname(community.getCname());
				tmp.setCaddr(community.getCaddr());
				tmp.setState(community.getState());
				tmp.setPerson(community.getPerson());
				tmp.setTel(community.getTel());
				tmp.setContent(community.getContent());
				communityService.save(tmp);
				
			}
		}catch(Exception ex){
			ex.printStackTrace();
			msg="小区信息保存失败";
		}finally{
			return "succ";
		}
	}
	public String show(){
		Community community=communityService.show(this.community.getCid());
		if(community.getBans().size()>0){
			JSONArray arrayOne =new JSONArray();
			SortedSet<Ban> bans=new TreeSet<Ban>(new Comparator<Ban>(){
				public int compare(Ban o1, Ban o2) {
					return o1.getBname().compareTo(o2.getBname());
				}				
			});
			bans.addAll(community.getBans());
			JSONObject rootJSON=new JSONObject();
			rootJSON.put("id", community.getCid());
			rootJSON.put("name",community.getCname());
			rootJSON.put("pId","0");
			arrayOne.add(rootJSON);
			for(Iterator<Ban> iter=bans.iterator();iter.hasNext();){
				Ban ban=iter.next();
				JSONObject banJSON=new JSONObject();
				banJSON.put("id", ban.getBid());
				banJSON.put("name",ban.getBname());
				banJSON.put("pId",community.getCid());
				arrayOne.add(banJSON);
				SortedSet<Unit> units=new TreeSet<Unit>(new Comparator<Unit>(){
					public int compare(Unit o1, Unit o2) {
						return o1.getUname().compareTo(o2.getUname());
					}				
				});
				units.addAll(ban.getUnits());
				for(Iterator<Unit> unit_Iter=units.iterator();unit_Iter.hasNext();){
					Unit unit=unit_Iter.next();
					JSONObject unitJSON=new JSONObject();
					unitJSON.put("id", unit.getUid());
					unitJSON.put("name",unit.getUname());
					unitJSON.put("pId",ban.getBid());
					arrayOne.add(unitJSON);
					SortedSet<Room> rooms=new TreeSet<Room>(new Comparator<Room>(){
						public int compare(Room o1, Room o2) {
							return o1.getRcode().compareTo(o2.getRcode());
						}				
					});
					rooms.addAll(unit.getRooms());
					for(Iterator<Room> room_Iter=rooms.iterator();room_Iter.hasNext();){
						Room room=room_Iter.next();
						JSONObject roomJSON=new JSONObject();
						roomJSON.put("id", room.getRid());
						roomJSON.put("name",room.getRcode());
						roomJSON.put("pId",unit.getUid());
						arrayOne.add(roomJSON);
					}
				}
			}
			resultObj=new JSONObject();
			resultObj.put("community", arrayOne);
			return "show";
		}else{
			msg="succ";
			return "succ";
		}
		
	}
	/**小区管理，分页查询*/
	public String query(){
		QueryFilter filter = new QueryFilter(getRequest()); 
	
		/**获取当前登录者*/
		User user=(User)super.getSession().getAttribute(SystemConstants.SESSION_CURRENT_USER);
		this.communitys=this.communityService.queryPage(filter, community==null?null:community.getCname(),user.getLoginid());
		super.setRownum(filter.getPagingBean().getTotalItems());
		super.setCurrentpage(Integer.parseInt(filter.getPagingBean().getStart()+"")/Integer.parseInt(filter.getPagingBean().getPageSize()+"")+1);
		super.setPageSize(Integer.parseInt(filter.getPagingBean().getPageSize()+""));
		return "query";
	}
	public List<Community> getCommunitys() {
		return communitys;
	}
	public void setCommunitys(List<Community> communitys) {
		this.communitys = communitys;
	}
	public Community getCommunity() {
		return community;
	}
	public void setCommunity(Community community) {
		this.community = community;
	}
	public String getMsg() {
		return msg;
	}
	public void setMsg(String msg) {
		this.msg = msg;
	}
	public List<Rule> getRules() {
		return rules;
	}
	public void setRules(List<Rule> rules) {
		this.rules = rules;
	}
	public JSONObject getResultObj() {
		return resultObj;
	}
	public void setResultObj(JSONObject resultObj) {
		this.resultObj = resultObj;
	}
	public List<ChargeRule> getChargeRules() {
		return chargeRules;
	}
	public void setChargeRules(List<ChargeRule> chargeRules) {
		this.chargeRules = chargeRules;
	}
	
}
